package com.battle.service.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.battle.pojo.dto.sirens.SelectSirensApiDto;
import com.battle.pojo.entity.Sirens;
import com.battle.pojo.httpUrl.all.*;
import com.battle.pojo.param.sirens.GetSirensListByTypeParam;
import com.battle.pojo.param.sirens.api.GetSirensListApiParam;
import com.battle.pojo.vo.sirens.GetSirensInfoApiVo;
import com.battle.pojo.vo.sirens.GetSirensListApiVo;
import com.battle.pojo.vo.sirens.api.*;
import com.battle.pojo.vo.sirens.api.details.GetMicroStationVo;
import com.battle.pojo.vo.sirens.api.details.GetSirensCarInfoVo;
import com.battle.pojo.vo.sirens.api.details.GetSirensOrderVo;
import com.battle.pojo.vo.sirens.api.details.GetWarPersonnelVo;
import com.battle.service.repository.in.SirensApiRepository;
import com.battle.service.repository.in.SirensRepository;
import com.battle.service.service.in.SirensApiService;
import com.battle.service.utils.JsonUtil;
import nirvana.core.domains.vo.PageResult;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 【描 述】：警情信息
 * 【环 境】：J2SE
 * 【详 细】：
 */
@Service
public class SirensApiServiceImpl implements SirensApiService{

    private final SirensApiRepository sirensApiRepository;
    private final SirensRepository sirensRepository;
    private final StringRedisTemplate stringRedisTemplate;
    private String httpUrl="https://zl.hzxfdd119.hangzhou.gov.cn";
    private static String sirensList = "sirens:list";

    public SirensApiServiceImpl(SirensApiRepository sirensApiRepository, SirensRepository sirensRepository, StringRedisTemplate stringRedisTemplate) {
        this.sirensApiRepository = sirensApiRepository;
        this.sirensRepository = sirensRepository;
        this.stringRedisTemplate = stringRedisTemplate;
    }


    /**
     * 获取警情列表
     *
     * @param param
     * @return
     */
    @Override
    public PageResult<GetSirensListApiDetailsVo> getSirensList(GetSirensListApiParam param) {
        List<GetSirensListApiDetailsVo> voList=new ArrayList<>();
        Long total=0L;

        String url=httpUrl+"/coc-fire/third/incidentList";
        long time = LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        String token="taihe01,1234qwer,"+time;

        JSONObject body = new JSONObject();
        //  LocalDate转换为时间戳
        if (param.getStartTime()!=null){
            body.put("startTime",param.getStartTime().atStartOfDay().toInstant(ZoneOffset.ofHours(8)).toEpochMilli());
        }
        if (param.getEndTime()!=null){
            body.put("endTime",param.getEndTime().atStartOfDay().toInstant(ZoneOffset.ofHours(8)).toEpochMilli());
        }
        if (CollectionUtil.isNotEmpty(param.getIncidentTypeCodes())){
            body.put("incidentTypeCodes",param.getIncidentTypeCodes());
        }
        if (ObjectUtil.isNotEmpty(param.getKeyword())) {
            body.put("keyword", param.getKeyword());
        }
        body.put("whetherPage","true");

        JSONObject page=new JSONObject();
        page.put("page",param.getCurrent());
        page.put("size",param.getSize());
        body.put("pagination",page);

        String result = HttpUtil.createPost(url)
                .header("token", token)
                .body(body.toString()).execute().body();

        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONObject pagination=data.getJSONObject("pagination");
        total = pagination.getLong("total");

        if (total!=null && total!=0){
            JSONArray list = data.getJSONArray("list");
            if (list!=null){
                HashMap<String, Object> map = new HashMap<>();
                for (int i = 0; i < list.size(); i++) {
                    JSONObject object = list.getJSONObject(i);

                    map.put(object.get("id").toString(),object.toJSONString());

                    GetSirensListApiDetailsVo vo = JsonUtil.toBean(object.toJSONString(), GetSirensListApiDetailsVo.class);
                    Long registerIncidentTime = object.getLong("registerIncidentTime");
                    vo.setRegisterIncidentDateTime(Instant.ofEpochMilli(registerIncidentTime).atZone(ZoneOffset.ofHours(8)).toLocalDateTime());

                    //获取出动机构数，和出动车辆数
                    Integer dispatchOrganization = object.getInteger("dispatchOrganization");
                    Integer dispatchVehicle = object.getInteger("dispatchVehicle");
                    String dispatchNumber=dispatchOrganization+"队"+dispatchVehicle+"车";
                    vo.setDispatchNumber(dispatchNumber);

                    //查看警情mp表，如果有的话，拿到对应的id
                    Sirens sirensByApiId = sirensRepository.getSirensByApiId(vo.getId());
                    if (sirensByApiId!=null){
                        vo.setSirensId(sirensByApiId.getId());
                        vo.setDetachmentPatrolStation(sirensByApiId.getDetachmentPatrolStation());
                        vo.setBattalionPatrolStation(sirensByApiId.getBattalionPatrolStation());
                        vo.setAlarmPanelId(sirensByApiId.getAlarmPanelId());
                    }
                    voList.add(vo);
                }
                stringRedisTemplate.opsForHash().putAll(sirensList,map);
            }
        }
        return new PageResult<>(voList,total);
    }

    /**
     * 获取警情详情
     *
     * @param id
     * @return
     */
    @Override
    public GetSirensInfoApiVo getSirensInfo(String id) {
        GetSirensInfoApiVo vo = new GetSirensInfoApiVo();

        Object cacheDetail = stringRedisTemplate.opsForHash().get(sirensList,id);
        if (cacheDetail!=null){
            JSONObject object = JSONObject.parseObject(cacheDetail.toString());
            vo.setExtra(object);
        }




        vo.setId(id);
        //获取案件详情
        ParticularsCase particularsCase = sirensApiRepository.selectParticularsCase(id);
        vo.setParticularsCase(particularsCase);
        //获取出动力量 出动车辆，参战人员，出动微站
        MobilizationForce mobilizationForce = new MobilizationForce();
        mobilizationForce.setCarInfo(getCarInfo(id));
        mobilizationForce.setWarPersonnel(getWarPersonnel(id));
        mobilizationForce.setMicroStations(getMicroStationVos(id));
        vo.setMobilizationForce(mobilizationForce);
//        //获取现场指挥
        vo.setFloorManager(getFloorManager(id));
        //获取现场反馈
        vo.setFieldFeedback(sirensApiRepository.selectFieldFeedback(id));
        //获取结案反馈
        vo.setClosingFeedback(sirensApiRepository.selectClosingFeedback(id));
        //获取报警记录
        vo.setAlarmInformation(sirensApiRepository.selectAlarmInformation(id));
        // 照片视频
        vo.setPictureVideo(getPictureViedVos(id));
        return vo;
    }

    @Override
    public PageResult<GetSirensListApiVo> getSirensListByType(GetSirensListByTypeParam param) {
        SelectSirensApiDto dto = new SelectSirensApiDto();
        BeanUtils.copyProperties(param, dto);
        dto.setType(param.getType());
        Page<GetSirensListApiVo> page = sirensApiRepository.getSirensListByType(dto);
        List<GetSirensListApiVo> list = page.getRecords();
        if (CollectionUtil.isNotEmpty(list)){
            list.forEach(v -> {
                //转换时间戳为LocaDateTime格式
                v.setLasjTime(Instant.ofEpochMilli(v.getLasj()).atZone(ZoneOffset.ofHours(8)).toLocalDateTime());
            });
        }
        return new PageResult<>(list, page);
    }


    /**
     * 根据案件id 查询指令
     * @param id
     * @return
     */
    List<FloorManager> getFloorManager(String id){
        List<FloorManager> floorManagers=new ArrayList<>();

        String url=httpUrl+"/coc-fire/third/findInstructions";
        long time = LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        String token="taihe01,1234qwer,"+time;

        JSONObject body = new JSONObject();
        body.put("incidentId",id);

        String result = HttpUtil.createPost(url)
                .header("token", token)
                .header("Content-Type", "application/json")
                .body(body.toString()).execute().body();

        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray data = jsonObject.getJSONArray("data");
        if (data!=null){
            for (int i = 0; i < data.size(); i++) {
                JSONObject object = data.getJSONObject(i);
                FloorManager floorManager = JsonUtil.toBean(object.toJSONString(), FloorManager.class);
                JSONArray jsonArray = object.getJSONArray("instructionRecordList");
                List<GetSirensOrderVo> orders=new ArrayList<>();
                if (jsonArray!=null){
                    for (int j = 0; j < jsonArray.size(); j++) {
                         object = jsonArray.getJSONObject(j);
                        GetSirensOrderVo sirensOrderVo = JsonUtil.toBean(object.toJSONString(), GetSirensOrderVo.class);
                        orders.add(sirensOrderVo);
                    }
                    floorManager.setOrders(orders);
                }
                floorManagers.add(floorManager);
            }
        }
        return floorManagers;
    }

    /**
     * 根据案件id获取作战车辆信息
     * @param id
     * @return
     */
    List<GetSirensCarInfoVo>  getCarInfo(String id){
        List<GetSirensCarInfoVo> floorManagers=new ArrayList<>();

        String url=httpUrl+"/coc-fire/third/findHandleOrganizationVehicles?incidentId="+id;
        long time = LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        String token="taihe01,1234qwer,"+time;

        String result = HttpUtil.createPost(url)
                .header("token", token)
                .header("Content-Type", "application/json")
                .execute().body();

        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray data = jsonObject.getJSONArray("data");
        if (data!=null){
            for (int i = 0; i < data.size(); i++) {
                JSONObject object = data.getJSONObject(i);
                GetSirensCarInfoVo floorManager = JsonUtil.toBean(object.toJSONString(), GetSirensCarInfoVo.class);
                floorManagers.add(floorManager);
            }
        }
        return floorManagers;
    }

    /**
     * 根据案件id获取参战人员
     * @param id
     * @return
     */
    List<GetWarPersonnelVo>  getWarPersonnel(String id){
        List<GetWarPersonnelVo> floorManagers=new ArrayList<>();

        String url=httpUrl+"/coc-fire/third/findVehiclePersonsByIncidentId?incidentId="+id;
        long time = LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        String token="taihe01,1234qwer,"+time;


        HttpRequest request = HttpUtil.createPost(url)
                .header("token", token)
                .header("Content-Type", "application/json");

        HttpResponse response = request.execute();
        String result = response.body();

        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray data = jsonObject.getJSONArray("data");
        if (data!=null){
            for (int i = 0; i < data.size(); i++) {
                JSONObject object = data.getJSONObject(i);
                GetWarPersonnelVo floorManager = JsonUtil.toBean(object.toJSONString(), GetWarPersonnelVo.class);
                JSONArray jsonArray = object.getJSONArray("organizationPersonName");
                if (jsonArray!=null){
                    floorManager.setOrganizationPersonCount(jsonArray.size());
                }else{
                    floorManager.setOrganizationPersonCount(0);
                }
                floorManagers.add(floorManager);
            }
        }
        return floorManagers;
    }

    /**
     * 根据案件id获取出动微站
     * @param id
     * @return
     */
    List<GetMicroStationVo>  getMicroStationVos(String id){
        List<GetMicroStationVo> floorManagers=new ArrayList<>();

        String url=httpUrl+"/coc-fire/third/findHandleMiniatureStation?incidentId="+id;
        long time = LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        String token="taihe01,1234qwer,"+time;

        String result = HttpUtil.createPost(url)
                .header("token", token)
                .header("Content-Type", "application/json")
                .execute().body();

        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray data = jsonObject.getJSONArray("data");
        if (data!=null){
            for (int i = 0; i < data.size(); i++) {
                JSONObject object = data.getJSONObject(i);
                GetMicroStationVo floorManager = JsonUtil.toBean(object.toJSONString(), GetMicroStationVo.class);
                floorManagers.add(floorManager);
            }
        }
        return floorManagers;
    }

    /**
     * 根据案件id获取附件信息
     * @param id
     * @return
     */
    List<PictureVideo>  getPictureViedVos(String id){
        List<PictureVideo> floorManagers=new ArrayList<>();

        String url=httpUrl+"/coc-fire/third/findAttachment?incidentId="+id;
        long time = LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
        String token="taihe01,1234qwer,"+time;

        String result = HttpUtil.createPost(url)
                .header("token", token)
                .header("Content-Type", "application/json")
                .execute().body();

        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray data = jsonObject.getJSONArray("data");
        if (data!=null){
            for (int i = 0; i < data.size(); i++) {
                JSONObject object = data.getJSONObject(i);
                PictureVideo floorManager = JsonUtil.toBean(object.toJSONString(), PictureVideo.class);
                floorManagers.add(floorManager);
            }
        }
        return floorManagers;
    }
}
